package com.jason.basicandroid.preference;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class PreferenceDemo extends Activity {
	private TextView tvFavoriteFruit = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tvFavoriteFruit = (TextView)findViewById(R.id.tvFavoriteFruit);
        
        setFavoriteFruitText();
    } 
    
    public void onBtnFavoriteFruitClick(View v) {
	   	Intent intent = new Intent() 
		    .setClass(this, FavoriteFruitPreference.class); 
		startActivityForResult(intent, 0);    	
    }
     
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
    	MenuInflater inflater = getMenuInflater(); 
    	inflater.inflate(R.menu.mainmenu, menu); 
    	return true; 
    } 
 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
       if (item.getItemId() == R.id.menu_favorite_fruit)  { 
    	   	Intent intent = new Intent() 
                   .setClass(this, FavoriteFruitPreference.class); 
    	   	startActivityForResult(intent, 0);
       } else if (item.getItemId() == R.id.menu_quit) { 
    	   	finish(); 
       }
       return true; 
    } 
 
    @Override 
    public void onActivityResult(int reqCode, int resCode, Intent data) { 
        super.onActivityResult(reqCode, resCode, data); 
        setFavoriteFruitText(); 
    }
    
    private void setFavoriteFruitText() {
    	SharedPreferences prefs = getSharedPreferences(
    			getResources().getString(R.string.pref_file),
    			MODE_PRIVATE);
    	String key = getResources().getString(R.string.selected_favorite_fruit);
    	String defaultValue = getResources().getString(R.string.favorite_fruit_option_default_value);
    	String option = prefs.getString(key, defaultValue);
    	String[] fruitText = getResources().getStringArray(R.array.favorite_fruit_options);
    	
    	String str = "Option is " + option + "(" + fruitText[Integer.parseInt(option)] + ")";
    	tvFavoriteFruit.setText(str);
    }
}